import { getLayerManagerState } from "../layer/layerManagerState";
import { removeLayer, LayerConfig, LayerType, addLayer } from "../layer/layerManage";
import { closePopup, createPopup } from "../popup/index";

// 分段配置  更新
export const SEGMENT_CONFIG = {
  pointsPerSegment: 1000, // 每段最大点数
  maxSegments: 100, // 最大分段数量
  segmentTypes: {
    NORMAL: 'normal', // 普通航迹线
    HIGHLIGHT: 'highlight' // 高亮航迹线（有催化剂状态）
  }
};

// 动画时长   更新
export const ANIMATION_DURATION = 1000;

// markerInfo 定义   更新
export let markerInfo: Record<
  string,
  {
    positions: [number, number]; // 当前位置
    trail: [number, number][]; // 原始航迹点（未分段）
    trailEnabled: boolean; // 航迹线是否启用
    popup: mapboxgl.Popup | null; // Popup 实例
    segments: {
      // 分段数据
      id: string; // 分段唯一标识
      points: [number, number][]; // 该段的坐标点数组
      pointCount: number; // 该段的点数
      type: string; // 分段类型
    }[];

  }
> = {};


// 航迹线分段数据源和图层ID格式// 修改航迹线ID生成函数，增加类型参数  更新
const getSegmentSourceId = (id: string, segmentId: number, type = SEGMENT_CONFIG.segmentTypes.NORMAL) =>
  `${id}-segment-${segmentId}-${type}`;

const getSegmentLayerId = (id: string, segmentId: number, type = SEGMENT_CONFIG.segmentTypes.NORMAL) =>
  `${id}-segment-${segmentId}-${type}`;


// 线性插值函数  更新
export const lerp = (start: [number, number], end: [number, number], fraction: number): [number, number] => {
  return [start[0] + (end[0] - start[0]) * fraction, start[1] + (end[1] - start[1]) * fraction];
};

// 计算朝向的函数  更新
export const calculateBearing = (start: [number, number], end: [number, number]): number => {
  const startLng = (start[0] * Math.PI) / 180;
  const startLat = (start[1] * Math.PI) / 180;
  const endLng = (end[0] * Math.PI) / 180;
  const endLat = (end[1] * Math.PI) / 180;

  const y = Math.sin(endLng - startLng) * Math.cos(endLat);
  const x = Math.cos(startLat) * Math.sin(endLat) - Math.sin(startLat) * Math.cos(endLat) * Math.cos(endLng - startLng);
  const bearing = (Math.atan2(y, x) * 180) / Math.PI;
  return (bearing + 360) % 360;
};


/**
 * 更新航迹点并按点数分段，同时创建对应的图层  更新
 * @param map - 地图对象
 * @param id - 标记ID
 * @param currentPoint - 当前坐标点 [lon, lat]
 * @param properties - 点的属性
 */
export const updateTrailAndSegmentByPoints = (map: any, id: string, currentPoint: [number, number], properties?: any) => {
  const marker = markerInfo[id];
  if (!marker || !marker.trailEnabled) return;

  // 更新原始航迹点
  marker.trail.push(currentPoint);
  // 检查是否有催化剂状态，决定是否添加到高亮航迹线
  const hasCatalystStatus = properties && properties.typesAndDosagesOfCatalysts && properties.typesAndDosagesOfCatalysts !== "";

  // 处理普通航迹线
  processSegment(map, id, currentPoint, properties, SEGMENT_CONFIG.segmentTypes.NORMAL);

  // 处理高亮航迹线（有催化剂状态的点）
  if (hasCatalystStatus) {
    processSegment(map, id, currentPoint, properties, SEGMENT_CONFIG.segmentTypes.HIGHLIGHT);
  }
};


/**
 * 处理分段逻辑 更新
 */
const processSegment = (map: any, id: string, currentPoint: [number, number], properties?: any, type?: string) => {
  const marker = markerInfo[id];

  // 确定使用哪个分段数组
  const segments = type === SEGMENT_CONFIG.segmentTypes.NORMAL ? marker.segments :
    marker.segments.filter(seg => seg.type === type);

  // 初始化分段（首次添加点）
  if (segments.length === 0) {
    const segmentId = 1;
    marker.segments.push({
      id: `${id}-segment-${segmentId}-${type}`,
      points: [currentPoint],
      pointCount: 1,
      type: type
    });

    // 创建第一个分段的数据源和图层
    createSegmentLayer(map, id, segmentId, currentPoint, properties, type);
  } else {
    // 获取当前活动分段
    const activeSegment = segments[segments.length - 1];

    // 添加点到当前分段
    activeSegment.points.push(currentPoint);
    activeSegment.pointCount++;

    // 检查是否达到分段阈值
    if (activeSegment.pointCount >= SEGMENT_CONFIG.pointsPerSegment) {
      const newSegmentId = segments.length + 1;

      // 创建新分段
      marker.segments.push({
        id: `${id}-segment-${newSegmentId}-${type}`,
        points: [currentPoint],
        pointCount: 1,
        type: type
      });

      // 创建新分段的数据源和图层
      createSegmentLayer(map, id, newSegmentId, currentPoint, properties, type);

      // 限制分段总数
      const allSegmentsOfType = marker.segments.filter(seg => seg.type === type);
      if (allSegmentsOfType.length > SEGMENT_CONFIG.maxSegments) {
        const removedSegment = allSegmentsOfType[0];
        const segmentId = parseInt(removedSegment.id.split('-')[2]);

        // 移除最早的分段图层和数据源
        removeSegmentLayer(map, id, segmentId, type);

        // 从markerInfo中删除
        const indexToRemove = marker.segments.findIndex(seg => seg.id === removedSegment.id);
        if (indexToRemove !== -1) {
          marker.segments.splice(indexToRemove, 1);
        }
      }
    }
  }
};


/**
 * 创建分段的数据源和图层   更新
 */
const createSegmentLayer = (
  map: any,
  id: string,
  segmentId: number,
  initialPoint: [number, number],
  properties?: any,
  type = SEGMENT_CONFIG.segmentTypes.NORMAL
) => {
  const sourceId = getSegmentSourceId(id, segmentId, type);
  const layerId = getSegmentLayerId(id, segmentId, type);

  // 确保properties包含catalystStatus
  const segmentProperties = {
    ...properties,
    catalystStatus: properties?.typesAndDosagesOfCatalysts || ""
  };

  // 创建数据源
  map.addSource(sourceId, {
    type: "geojson",
    data: {
      type: "FeatureCollection",
      features: [{
        type: "Feature",
        geometry: {
          type: "LineString",
          coordinates: [initialPoint]
        },
        properties: segmentProperties
      }]
    }
  });

  // 根据分段类型设置不同的样式
  const paint = type === SEGMENT_CONFIG.segmentTypes.HIGHLIGHT
    ? {
      "line-width": 5,
      "line-color": "#93FA64", // 高亮航迹线使用绿色
      "line-opacity": 0.8
    }
    : {
      "line-width": 4,
      "line-color": "#1841AF", // 普通航迹线使用淡蓝色
      "line-opacity": 0.5
    };

  const layer: LayerConfig = {
    id: layerId,
    type: LayerType.Line,
    source: sourceId,
    paint: paint
  };

  addLayer(getLayerManagerState(map), layer);

  // 将图层放置在标记下方
  if (map.getLayer(`${id}`)) {
    map.moveLayer(layerId, `${id}`);
  }
};



/**
 * 更新航迹线显示（直接更新各分段数据源） 更新
 */
export const updateTrailDisplay = (map: any, id: string, properties?: any) => {
  const marker = markerInfo[id];
  if (!marker || !marker.trailEnabled) return;

  // 确保properties包含catalystStatus
  const segmentProperties = {
    ...properties,
    catalystStatus: properties?.typesAndDosagesOfCatalysts || ""
  };

  // 遍历所有分段，更新对应数据源
  marker.segments.forEach((segment) => {
    const segmentId = parseInt(segment.id.split('-')[2]);
    const sourceId = getSegmentSourceId(id, segmentId, segment.type);

    // 检查并创建数据源
    if (!map.getSource(sourceId)) {
      map.addSource(sourceId, {
        type: "geojson",
        data: {
          type: "FeatureCollection",
          features: [
            {
              type: "Feature",
              geometry: {
                type: "LineString",
                coordinates: segment.points
              },
              properties: segmentProperties
            }
          ]
        }
      });
    }

    // 更新数据源
    const source = map.getSource(sourceId);
    if (source) {
      source.setData({
        type: "FeatureCollection",
        features: [
          {
            type: "Feature",
            geometry: {
              type: "LineString",
              coordinates: segment.points
            },
            properties: segmentProperties
          }
        ]
      });
    }
  });
};


/**
 * 移除分段的图层和数据源  更新
 */
const removeSegmentLayer = (map: any, id: string, segmentId: number, type = SEGMENT_CONFIG.segmentTypes.NORMAL) => {
  const layerId = getSegmentLayerId(id, segmentId, type);
  const sourceId = getSegmentSourceId(id, segmentId, type);

  if (map.getLayer(layerId)) {
    map.removeLayer(layerId);
  }

  if (map.getSource(sourceId)) {
    map.removeSource(sourceId);
  }
};


/**
 * 删除航迹线（移除图层和数据源，清除内存中的分段数据）  更新
 */
export const removeTrail = (map: any, id: string) => {
  const marker = markerInfo[id];
  if (!marker) return;

  // 移除所有分段图层和数据源
  marker.segments.forEach((segment) => {
    const segmentId = parseInt(segment.id.split('-')[2]);
    const type = segment.type;
    const layerId = getSegmentLayerId(id, segmentId, type);
    const sourceId = getSegmentSourceId(id, segmentId, type);

    if (map.getLayer(layerId)) {
      map.removeLayer(layerId);
    }

    if (map.getSource(sourceId)) {
      map.removeSource(sourceId);
    }
  });

  // 关闭 Popup
  if (marker.popup) {
    closePopup(`popup-${id}`);
  }

  // 清除内存中的分段数据
  marker.segments = [];
  marker.trail = [];
  marker.trailEnabled = false;
};



/**
 * 移除标记和航迹线
 */
export const removeMarker = (map: any, id: string) => {
  if (markerInfo[id]) {
    // 先删除航迹线（清除所有数据）
    removeTrail(map, id);

    // 移除标记图层
    removeLayer(getLayerManagerState(map), `${id}`);

    // 移除 Popup
    if (markerInfo[id].popup) {
      markerInfo[id].popup = null;
      closePopup(`popup-${id}`);
    }

    // 更新 ID 列表
    delete markerInfo[id];
  }
};

/**
 *  创建popup
 */
export const createPopupInfo = (map: any, id: string, position: [number, number], html: string) => {
  const popup = createPopup(map, `popup-${id}`, position, html);
  markerInfo[id].popup = popup;
};


/**
 *  移除popup
 */
export const removePopup = (map: any, id: string) => {
  if (markerInfo[id] && markerInfo[id].popup) {
    // 移除 Popup
    markerInfo[id].popup.remove();
    closePopup(`popup-${id}`);
  }
};


/**
 * 更新popup内容
 */
export const updatePopupInfo = (map: any, id: string, html: string) => {
  if (markerInfo[id] && markerInfo[id].popup) {
    markerInfo[id].popup.setHTML(html);
  }
};

/**
 * 更新popup位置
 */
export const updatePopupPosition = (map: any, id: string, position: [number, number]) => {
  if (markerInfo[id] && markerInfo[id].popup) {
    markerInfo[id].popup.setLngLat(position);
  }
};


// 实时飞行popup展示
export const realTimeLayer = (options: any) => {
  if (JSON.stringify(options) == "{}") {
    return;
  }
  return `<div style="
    background: #FFFFFF;
    border-radius: 6px;
    padding: 6px;
    min-width: 150px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    font-family: Arial, sans-serif;
  ">
    <div style="
      display: flex;
      align-items: center;
      gap: 4px;
      margin-bottom: 6px;
      padding-bottom: 4px;
      border-bottom: 1px solid #F0F0F0;
    ">
      <div style="
        background: #437EF1;
        color: white;
        padding: 1px 4px;
        border-radius: 3px;
        font-size: 10px;
      ">飞行中</div>
      <div style="
        color: #437EF1;
        font-size: 11px;
        font-weight: 500;
      ">${options.flightNumber || "B3836"}</div>
    </div>
    <div style="display: grid; grid-template-columns: 1fr 1fr; text-align: center;">
      <div>
        <div style="color: #909399; font-size: 9px;">海拔高度</div>
        <div style="color: #437EF1; font-size: 11px; font-weight: 500; font-family: DIN;">
          ${options.altitude || "0"
    }<span style="font-size: 9px; color: #909399; margin-left: 1px;">米</span>
        </div>
      </div>
      <div>
        <div style="color: #909399; font-size: 9px;">飞行速度</div>
        <div style="color: #437EF1; font-size: 11px; font-weight: 500; font-family: DIN;">
        </div>
      </div>
      <div>
        <div style="color: #909399; font-size: 9px;">经度</div>
        <div style="color: #437EF1; font-size: 11px; font-weight: 500; font-family: DIN;">
          ${Number(options.longitude) || "0"}
        </div>
      </div>
      <div>
        <div style="color: #909399; font-size: 9px;">纬度</div>
        <div style="color: #437EF1; font-size: 11px; font-weight: 500; font-family: DIN;">
          ${Number(options.latitude) || "0"}
        </div>
      </div>
    </div>
  </div>`;
};





